﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Text;
using System.Windows.Forms;
namespace HBAClient
{
    static class Util
    {
        static public string INOUT_DEFAULT_MSG = "Please set your input and press the Save button"; // Default user message for In and Out forms
        static public string DEFAULT_BANK_NAME = "New Bank Name"; // Default name for new bank
        static public Decimal STARTING_BALANCE = 0; // Default balance amount
        static public int BANK_ID_ERROR = -999; // ID retunr in case of error
        static public string PLAN_NOT_CLOSED = "NO"; // No in the Closed column of planns
        static public string PLAN_CLOSED = "YES"; // Yes in the Closed column of planns
        static public string PLAN_NOT_EXIST = "PlanNotExist"; // Defining plan which not exist
        static public string DEFAULT_BANK_MSG = "To delete a record please select and click on delete"; // Default user message for Banks forms
        //static public enum REOCCURRENCE { ONCE = 1, MONTHLY, YEARLY };
        static public string ONCE = "ONCE"; // Reoccurrence type
        static public string MONTHLY = "MONTHLY"; // Reoccurrence type
        static public string YEARLY = "YEARLY"; // Reoccurrence type
        static public string DOUBLE_MONTHLY = "DOUBLEMONTHLY"; // Reoccurrence type
        static public int END_YEAR = 2079; // Expeiretion year
        static public DateTime EXPIRATION_DATE = new DateTime(2079,01,01);
        static public int ADD_TO_CURR_MONTH = 1; // How much monthes to add to the current month for Sum plan
        
        // Insert new bill record from In and Out forms
        static public void SaveRecord(long lUserID, DateTime dtDate, Decimal nInSum, Decimal nOutSum, 
            long lBankID, string strSource)
        {
            nInSum = Math.Round(nInSum, 2);
            nOutSum = Math.Round(nOutSum, 2);

            HBADBDataContext dbCon = new HBADBDataContext();
            Bill billRecord = new Bill();
            // Set new data to the new record
            billRecord.UserID = lUserID;
            billRecord.Source = strSource;
            billRecord.OutSum = nOutSum;
            billRecord.InSum = nInSum;
            billRecord.Date = dtDate;
            billRecord.BankID = lBankID;
            billRecord.Balance = STARTING_BALANCE;
            
            // Prapare for inserting
            dbCon.Bills.InsertOnSubmit(billRecord); 

            // Make the insert
            dbCon.SubmitChanges(); 
        }

        // Insert new plan record from Bank form Monthly
        static public void SavePlanRecordMonthly(string strBankName, DateTime dtPlanDate, string strSource,
            Decimal nPlanOut, Decimal nPlanIn, string strReoccurrence, DateTime dtExpired)
        {
            while (dtPlanDate < dtExpired)
            {
                SavePlanRecord(strBankName, dtPlanDate, strSource, nPlanOut, nPlanIn, strReoccurrence);
                dtPlanDate = dtPlanDate.AddMonths(1);
            }
        }

        // Insert new plan record from Bank form Monthly
        static public void SavePlanRecordDoubleMonthly(string strBankName, DateTime dtPlanDate, string strSource,
            Decimal nPlanOut, Decimal nPlanIn, string strReoccurrence, DateTime dtExpired)
        {
            while (dtPlanDate < dtExpired)
            {
                SavePlanRecord(strBankName, dtPlanDate, strSource, nPlanOut, nPlanIn, strReoccurrence);
                dtPlanDate = dtPlanDate.AddMonths(2);
            }
        }


        // Insert new plan record from Bank form Yearly
        static public void SavePlanRecordYearly(string strBankName, DateTime dtPlanDate, string strSource,
            Decimal nPlanOut, Decimal nPlanIn, string strReoccurrence, DateTime dtExpired)
        {
            while (dtPlanDate < dtExpired)
            {
                SavePlanRecord(strBankName, dtPlanDate, strSource, nPlanOut, nPlanIn, strReoccurrence);
                dtPlanDate = dtPlanDate.AddYears(1);
            }
        }
        
        // Insert new plan record from Bank form
        static public void SavePlanRecord(string strBankName,DateTime dtPlanDate, string strSource,
            Decimal nPlanOut, Decimal nPlanIn, string strReoccurrence)
        {
            nPlanIn = Math.Round(nPlanIn, 2);
            nPlanOut = Math.Round(nPlanOut, 2);

            HBADBDataContext dbCon = new HBADBDataContext();
            Plan planRecord = new Plan();
            // Set new data to the new record
            planRecord.UserID = Program.GetUserID();
            planRecord.BankID = GetNewBankID(strBankName);
            planRecord.Source = strSource;
            planRecord.Date = dtPlanDate;
            planRecord.OutSum = nPlanOut;
            planRecord.InSum = nPlanIn;
            planRecord.Reoccurrence = strReoccurrence;
            planRecord.Closed = PLAN_NOT_CLOSED;

            // Prapare for inserting
            dbCon.Plans.InsertOnSubmit(planRecord);

            // Make the insert
            dbCon.SubmitChanges();
        }
        // Insert new bank record (banks table)
        static public bool SaveNewBank(long lUserID, string strBankName)
        {
            // Check if current bank name is exist
            long nNewID = BANK_ID_ERROR;

            try
            {
                HBADBDataContext dbConBanks = new HBADBDataContext();
                // Build the query to get the bank name
                var query = from ban in dbConBanks.Banks
                            where ban.BankName == strBankName
                            select new
                            {
                                BankNewID = ban.BankID
                            };


                nNewID = query.First().BankNewID;
            }
            catch
            {
                nNewID = BANK_ID_ERROR;
            }


            bool bSavedSuccess = false;
            long nNewBankIdFoud;
            HBADBDataContext dbCon = new HBADBDataContext();
            // Check if bank name is already exist
            if (nNewID == BANK_ID_ERROR) // Not exist
            {
                // Add new bank entity
                Bank bankRecord = new Bank();
                // Set data to the new bank entity
                bankRecord.BankName = strBankName;
                // Prapare for inserting
                dbCon.Banks.InsertOnSubmit(bankRecord);
                // Make the insert
                dbCon.SubmitChanges();

                // Get bank ID by bank name
                nNewBankIdFoud = GetNewBankID(strBankName);
            }
            else // Exist
            {
                nNewBankIdFoud = nNewID;
            }
            // Add new record to Balances
            // Add new balances entity
            Balance balRecord = new Balance();

            // Check if bank ID is valid
            if (BANK_ID_ERROR == nNewBankIdFoud) // Not Valid
            {
                return false;
            }
            else // Valid
            {
                if (nNewID == BANK_ID_ERROR) // New Bank, need new balances record
                {
                    
                    // Set new data to the balances entity
                    balRecord.BankID = nNewBankIdFoud;
                    balRecord.UserID = lUserID;
                    balRecord.CurrentBalance = STARTING_BALANCE;
                    // Prapare for inserting
                    dbCon.Balances.InsertOnSubmit(balRecord);
                    // Make the insert
                    dbCon.SubmitChanges();
                    bSavedSuccess = true;
                }
                else // Bank exist so balances record is exist also, need to update
                {
                    if (IfUserExistForBank(nNewID, lUserID)) // Current UserID & BankID record exist
                    {
                        // Do nothing, the balance record is exist
                    }
                    else
                    {
                        // Set new data to the balances entity
                        balRecord.BankID = nNewID;
                        balRecord.UserID = lUserID;
                        balRecord.CurrentBalance = STARTING_BALANCE;
                        // Prapare for inserting
                        dbCon.Balances.InsertOnSubmit(balRecord);
                        // Make the insert
                        dbCon.SubmitChanges();
                        bSavedSuccess = true;
                    }
                }
            }

            return bSavedSuccess;
        }
        static private bool IfUserExistForBank(long lBankID, long lUserID)
        {
            // Check if current bank name is exist
            bool bUserExist = false;
            long lUserNewID = -999;

            try
            {
                HBADBDataContext dbConBalances = new HBADBDataContext();
                // Build the query to get the bank name
                var query = from ban in dbConBalances.Balances
                            where ban.BankID == lBankID && ban.UserID == lUserID
                            select new
                            {
                                UserNewID = ban.UserID
                            };


                lUserNewID = query.First().UserNewID;
                if (lUserNewID == -999)
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
            if (lUserNewID != -999)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        // Get balance by userID and BankID
        static private Decimal GetOldBalance(long lUserID, long lBankID)
        {
            Decimal nNewBalance = STARTING_BALANCE;
            try
            {
                HBADBDataContext dbConBalance = new HBADBDataContext();
                // Build query to get the balance
                var query = from bal in dbConBalance.Balances
                            where bal.BankID == lBankID && bal.UserID == lUserID
                            select new
                            {
                                BalanceVal = bal.CurrentBalance
                            };

                // Set the received balance to temp variable
                nNewBalance = query.First().BalanceVal;
            }
            catch { }
            return nNewBalance;
        }
        // Get BankID by bank name
        static public long GetNewBankID(string strBankName)
        {
            long nNewID = BANK_ID_ERROR;
            try
            {
                HBADBDataContext dbCon = new HBADBDataContext();
                // Build the query to get the bank name
                var query = from ban in dbCon.Banks
                            where ban.BankName == strBankName
                            select new
                            {
                                BankNewID = ban.BankID
                            };

                nNewID = query.First().BankNewID;
            }
            catch { }
            return nNewID;
        }
        // Update existing balance with a new one by UserID and BankID
        static public void SaveNewBalance(long lUserID, long lBankID, Decimal nNewBalance)
        {
            nNewBalance = Math.Round(nNewBalance, 2);

            HBADBDataContext dbCon = new HBADBDataContext();
            // Set b to be the record of UserID and BankID
            Balance b = dbCon.Balances.Where(x => x.UserID == lUserID && x.BankID == lBankID).First();
            // Update the record with the new balance
            b.CurrentBalance = nNewBalance;
            // Make the changes
            dbCon.SubmitChanges();
        }
        // Set the balance field of bills record by BillID
        static private void SaveNewBalanceToBills(long lBillIDParam, Decimal nNewBalanceToUpdate)
        {
            nNewBalanceToUpdate = Math.Round(nNewBalanceToUpdate, 2);

            HBADBDataContext dbCon = new HBADBDataContext();
            // Set b to be the record of the provided billID

            Bill b = dbCon.Bills.Where(x => x.BillID == lBillIDParam).First();
            // Update the record with the new balance
            b.Balance = nNewBalanceToUpdate;
            // Make the changes
            dbCon.SubmitChanges();
        }
        // Populate combo box with sources from current UserID
        static public void SetSources(ref ComboBox cmbSource)
        {
            HBADBDataContext db = new HBADBDataContext();
            // Build the query to get the sources
            var query2 = from bill in db.Bills
                         where bill.UserID == Program.GetUserID()
                         select new
                         {
                             Source = bill.Source
                         };

            query2 = query2.Distinct();
            cmbSource.Items.Clear();
            
            foreach (var item in query2)
            {
                cmbSource.Items.Add(item.Source);
            }
            //cmbSource.DisplayMember = "Source";
            //cmbSource.ValueMember = "Source";
            //cmbSource.DataSource = query2.Distinct();
        }

        // Populate combo box with reoccurrences
        static public void SetReoccurrences(ref ComboBox cmbReoccurences)
        {
            cmbReoccurences.Items.Clear();
            cmbReoccurences.Items.Add(ONCE);
            cmbReoccurences.Items.Add(MONTHLY);
            cmbReoccurences.Items.Add(YEARLY);
            cmbReoccurences.Items.Add(DOUBLE_MONTHLY);
            cmbReoccurences.SelectedIndex = 0;
        }

        // Populate combo box with sobanks from current UserID
        static public void SetBanks(ref ComboBox cmbBank)
        {
            HBADBDataContext db = new HBADBDataContext();
            // Build the query to get the banks
            var query = from balance in db.Balances
                        join bank in db.Banks on balance.BankID equals bank.BankID
                        where balance.UserID == Program.GetUserID()
                        select new
                        {
                            BankName = bank.BankName,
                            BankID = bank.BankID
                        };
            cmbBank.DisplayMember = "BankName";
            cmbBank.ValueMember = "BankID";
            cmbBank.DataSource = query.Distinct();
        }
        // Populate combo toolstrip box with sobanks from current UserID
        static public void SetBanks(ref ToolStripComboBox tscmbBank)
        {
            tscmbBank.Items.Clear();
            HBADBDataContext db = new HBADBDataContext();
            // Build the query to get the banks
            var query = from balance in db.Balances
                        join bank in db.Banks on balance.BankID equals bank.BankID
                        where balance.UserID == Program.GetUserID()
                        select new
                        {
                            BankName = bank.BankName,
                            BankID = bank.BankID
                        };
            // Run on all the result banks and insert them into the combo box
            foreach (var currItem in query.Distinct())
            {
                tscmbBank.Items.Add(currItem.BankName);
            }
        }
        // Deleting bill record by billID
        static public void DeleteBillRecord(long lBillID)
        {
            HBADBDataContext dbCon = new HBADBDataContext();
            // Build the query to get the UserId and BankID of wanted record to delete
            var query = from bil in dbCon.Bills
                        where bil.BillID == lBillID
                        select new
                        {
                            UserVal = bil.UserID,
                            BankVal = bil.BankID,
                        };

            // Save the received BankID and UserID
            long lUserID = query.First().UserVal;
            long lBankID = query.First().BankVal;

            // Build the record definition for the wanted record to delete
            Bill toDelete = dbCon.Bills.Single(p => p.BillID == lBillID);
            // Prapare to delete
            dbCon.Bills.DeleteOnSubmit(toDelete);
            // Make the delete
            dbCon.SubmitChanges();

            // Reorder balances in bills and get the new final balance for this UserID and BankID
            Decimal nNewBalanceAfterDelete = RunOrderBills(lUserID, lBankID);

            // Save new balance to balances table
            SaveNewBalance(lUserID, lBankID, nNewBalanceAfterDelete);
        }
        // Update all the balances in the bills for current UserID and BankID
        static public Decimal RunOrderBills(long lUserID, long lBankID)
        {
            HBADBDataContext db = new HBADBDataContext();
            Decimal nReturnBalance = STARTING_BALANCE;
            Decimal nTempBal = STARTING_BALANCE;

            // Build the query to get the bills records of current UserID and BankID
            var query = from bil in db.Bills
                        where bil.UserID == lUserID && bil.BankID == lBankID
                        select new
                        {
                            BilID = bil.BillID,
                            Bal = bil.Balance,
                            InSum = bil.InSum,
                            OutSum = bil.OutSum,
                            DateIs = bil.Date
                        };
            // Update balances with previouse balance and In and Out
            foreach (var currItem in query.OrderBy(a => a.DateIs))
            {
                Decimal nCurrNewBal = nTempBal + currItem.InSum - currItem.OutSum;
                nCurrNewBal = Math.Round(nCurrNewBal, 2);
                SaveNewBalanceToBills(currItem.BilID, nCurrNewBal);
                nTempBal = nCurrNewBal;
            }

            // Return the last balance
            nReturnBalance = nTempBal;
            return nReturnBalance;
        }
        static public string SavePlan(string strBankName, DateTime dtPlanDate, string strSource, Decimal nPlanOut,
            Decimal nPlanIn, string strReoccurrence, DateTime dtExpirationDate)
        {
            nPlanIn = Math.Round(nPlanIn, 2);
            nPlanOut = Math.Round(nPlanOut, 2);

            string strMessage = "Plan record saved.";

            // Check if exist
            int nGetPlanResultCount = Util.GetExistingPlanCount(strBankName, dtPlanDate, strSource,
                strReoccurrence);
            if (nGetPlanResultCount < 1) // plan not exist
            {
                //MessageBox.Show("Plan not exist");
                // Insert new plan
                InsertPlan(strBankName,dtPlanDate, strSource, nPlanOut, nPlanIn, strReoccurrence, dtExpirationDate);
            }
            else // Plan Exist
            {
                DialogResult dl = MessageBox.Show("Plan already exist. Count " + nGetPlanResultCount + 
                    ". Want to update?", "Update existing plan", MessageBoxButtons.OKCancel);

                if (dl == DialogResult.OK)
                {
                    // Update
                    UpdatePlan(strBankName, dtPlanDate, strSource, nPlanOut, nPlanIn,
                        strReoccurrence, dtExpirationDate);
                }
                else
                {
                    strMessage = "";
                }
            }
            return strMessage;
        }
        static string UpdatePlan(string strBankName,DateTime dtPlanDate,
            string strSource, Decimal nPlanOut, Decimal nPlanIn, string strReoccurrence,
            DateTime dtExpirationDate)
        {
            nPlanIn = Math.Round(nPlanIn, 2);
            nPlanOut = Math.Round(nPlanOut, 2);

            DeletePlanRecord(strBankName, dtPlanDate, strSource, strReoccurrence);
            return InsertPlan(strBankName, dtPlanDate, strSource, nPlanOut, nPlanIn, strReoccurrence, dtExpirationDate);
        }
        static public int DeletePlanRecord(string strBankName,DateTime dtPlanDate, string strSource, string strReoccurrence)
        {
            HBADBDataContext db = new HBADBDataContext();
            int nRecordsDeleted = 0;

            var query = from plan in db.Plans
                        join bank in db.Banks on plan.BankID equals bank.BankID
                        where plan.UserID == Program.GetUserID() && bank.BankName == strBankName &&
                        plan.Source.ToUpper() == strSource.ToUpper() &&
                        plan.BankID == GetNewBankID(strBankName) &&
                        plan.Reoccurrence.ToUpper() == strReoccurrence.ToUpper() &&
                        plan.Closed.ToUpper() == PLAN_NOT_CLOSED
                        select plan;

            if (strReoccurrence == ONCE)
            {
                query = from plan in db.Plans
                        join bank in db.Banks on plan.BankID equals bank.BankID
                        where plan.UserID == Program.GetUserID() && bank.BankName == strBankName &&
                        plan.Source.ToUpper() == strSource.ToUpper() &&
                        plan.BankID == GetNewBankID(strBankName) &&
                        plan.Date == dtPlanDate &&
                        plan.Reoccurrence.ToUpper() == strReoccurrence.ToUpper() &&
                        plan.Closed.ToUpper() == PLAN_NOT_CLOSED
                        select plan;
            }

            //plan.Date > DateTime.Now.AddMonths(-10)

            nRecordsDeleted = query.Count();
            // Prapare to delete
            foreach (var detail in query)
            {
                db.Plans.DeleteOnSubmit(detail);
            }
            //tblPeople toDelete = db.tblPeoples.Decimal(p => p.id == selectedID);
            // Prapare to delete
            //db.Plans.DeleteOnSubmit(query);

            // Make the delete
            db.SubmitChanges();
            return nRecordsDeleted;
        }

        //static void DeletePlan(string strBankName, DateTime dtPlanDate,
        //  string strSource, string strReoccurrence)
        //{
        //    HBADBDataContext db = new HBADBDataContext();

        //    var query = from plan in db.Plans
        //                join bank in db.Banks on plan.BankID equals bank.BankID
        //                where plan.UserID == Program.GetUserID() && bank.BankName == strBankName &&
        //                plan.Date > DateTime.Now.AddMonths(1) && plan.Source.ToUpper() == strSource.ToUpper() &&
        //                plan.BankID == GetNewBankID(strBankName) &&
        //                plan.Reoccurrence.ToUpper() == strReoccurrence.ToUpper() &&
        //                plan.Closed.ToUpper() == PLAN_NOT_CLOSED
        //                select plan;

        //    // Prapare to delete
        //    foreach (var detail in query)
        //    {
        //        db.Plans.DeleteOnSubmit(detail);
        //    }
        //    //tblPeople toDelete = db.tblPeoples.Decimal(p => p.id == selectedID);
        //    // Prapare to delete
        //    //db.Plans.DeleteOnSubmit(query);
            
        //    // Make the delete
        //    db.SubmitChanges();
        //}

        static string InsertPlan(string strBankName, DateTime dtPlanDate, string strSource, Decimal nPlanOut,
            Decimal nPlanIn, string strReoccurrence, DateTime dtExpirationDate)
        {
            nPlanIn = Math.Round(nPlanIn, 2);
            nPlanOut = Math.Round(nPlanOut, 2);

            string strMessage = "Plan saved successfully";
            switch (strReoccurrence)
            {
                case "ONCE":
                    SavePlanRecord(strBankName, dtPlanDate, strSource, nPlanOut, nPlanIn, strReoccurrence);
                    break;
                case "MONTHLY":
                    SavePlanRecordMonthly(strBankName, dtPlanDate, strSource, nPlanOut, nPlanIn, strReoccurrence,
                        dtExpirationDate);
                    break;
                case "DOUBLEMONTHLY":
                    SavePlanRecordDoubleMonthly(strBankName, dtPlanDate, strSource, nPlanOut, nPlanIn, strReoccurrence,
                        dtExpirationDate);
                    break;
                case "YEARLY":
                    SavePlanRecordYearly(strBankName, dtPlanDate, strSource, nPlanOut, nPlanIn, strReoccurrence,
                        dtExpirationDate);
                    break;
                default:
                    strMessage = "Plan not saved. Reoccurrence is invalid.";
                    break;
            }
            return strMessage;
            //lblMessage.Text = strMessage;
        }
        static public DateTime GetExpirationDate(long lPlanID, string strBank, string strPlanSource,
            string strPlanReoccurrence, string strStatus)
        {
            DateTime dtReturn = EXPIRATION_DATE;

            try
            {
                HBADBDataContext db = new HBADBDataContext();

                var query = from plan in db.Plans
                            join bank in db.Banks on plan.BankID equals bank.BankID
                            where plan.UserID == Program.GetUserID() && bank.BankName == strBank &&
                            plan.Source.ToUpper() == strPlanSource.ToUpper() &&
                            plan.BankID == GetNewBankID(strBank) &&
                            plan.Reoccurrence.ToUpper() == strPlanReoccurrence.ToUpper() &&
                            plan.Closed.ToUpper() == strStatus.ToUpper() // && plan.Date == dtPlanDate
                            select plan.Date;

                dtReturn = query.Max();
            }
            catch { }

            return dtReturn;
        }

        static public int GetExistingPlanCount(string strBankName, DateTime dtPlanDate, string strPlanSource, 
            string strPlanReoccurrence)
        {
            //string strResult = PLAN_NOT_EXIST;
            int nReturnCountRecords = 0;

            HBADBDataContext db = new HBADBDataContext();

            var query = from plan in db.Plans
                        join bank in db.Banks on plan.BankID equals bank.BankID
                        where plan.UserID == Program.GetUserID() && bank.BankName == strBankName &&
                        plan.Source.ToUpper() == strPlanSource.ToUpper() &&
                        plan.BankID == GetNewBankID(strBankName) &&
                        plan.Reoccurrence.ToUpper() == strPlanReoccurrence.ToUpper() &&
                        plan.Closed.ToUpper() == PLAN_NOT_CLOSED // && plan.Date == dtPlanDate
                        select new { plan.Source };

            // Check if reoccurrence is ONCE
            if (strPlanReoccurrence == ONCE) // Is ONCE
            {
                query = from plan in db.Plans
                        join bank in db.Banks on plan.BankID equals bank.BankID
                        where plan.UserID == Program.GetUserID() && bank.BankName == strBankName &&
                        plan.Source.ToUpper() == strPlanSource.ToUpper() &&
                        plan.Date == dtPlanDate &&
                        plan.BankID == GetNewBankID(strBankName) &&
                        plan.Reoccurrence.ToUpper() == strPlanReoccurrence.ToUpper() &&
                        plan.Closed.ToUpper() == PLAN_NOT_CLOSED // && plan.Date == dtPlanDate
                        select new { plan.Source };
            }
                  
            nReturnCountRecords = query.Count();
            
            return nReturnCountRecords;
        }

        // Get last balance by User, Bank, Month and Year
        static public Decimal GetLastBalanceByDate(long lUserID, long lBankID, DateTime dtResetDate)
        {
            HBADBDataContext db = new HBADBDataContext();
            Decimal nReturnBalance = STARTING_BALANCE;
            Decimal nTempBal = STARTING_BALANCE;

            // Build the query to get the bills records of current UserID and BankID until the wanted date
            var query = from bil in db.Bills
                        where bil.UserID == lUserID && bil.BankID == lBankID &&
                        //bil.Date <= dtEndDatePick.Value.Date.AddDays(1)
                        bil.Date < dtResetDate
                        select new
                        {
                            BilID = bil.BillID,
                            Bal = bil.Balance,
                            InSum = bil.InSum,
                            OutSum = bil.OutSum,
                            DateIs = bil.Date
                        };


            // Get balance
            foreach (var currItem in query.OrderBy(a => a.DateIs))
            {
                Decimal nCurrNewBal = nTempBal + currItem.InSum - currItem.OutSum;
                //SaveNewBalanceToBills(currItem.BilID, nCurrNewBal);
                nTempBal = nCurrNewBal;
            }

            // Return the last balance
            nReturnBalance = nTempBal;
            return nReturnBalance;
        }
    }
}
